package com.xmbandu.app.home.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.xmbandu.app.R;
import com.xmbandu.app.adapter.BookAdapter;
import com.xmbandu.app.base.BaseFragment;
import com.xmbandu.app.bean.BookListBean;
import com.xmbandu.app.httpnet.BaseEntity;
import com.xmbandu.app.httpnet.RetrofitFactory;
import com.xmbandu.app.utils.CommonUtils;
import com.xmbandu.app.utils.NetUtil;
import com.xmbandu.app.view.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wmq on 2019-04-26.
 */

@SuppressLint("ValidFragment")
public class SimpleCardFragment extends BaseFragment {

    private String mTitle;
    private TextView tvAll;
    private RecyclerView rvBook;
    private BookAdapter bookAdapter;
    private List<BookListBean.ListBean> bookList;
    private int edBookPage = 1;
    private int sBookPage = 1;

    public static SimpleCardFragment getInstance(String title) {
        SimpleCardFragment sf = new SimpleCardFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_simple_card, null);
        rvBook = v.findViewById(R.id.rv_book);
        tvAll = v.findViewById(R.id.tv_all);
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bookList = new ArrayList<>();
        bookAdapter = new BookAdapter(R.layout.item_book, bookList);
        rvBook.setLayoutManager(new GridLayoutManager(getContext(), 2, LinearLayoutManager.VERTICAL, false));
        rvBook.addItemDecoration(new GridSpacingItemDecoration(2, CommonUtils.dip2px(getContext(), 10), false));
        rvBook.setAdapter(bookAdapter);

        if (mTitle==null)
            return;
        if (mTitle.equals("教育")) {
            getList("0", edBookPage);
        } else if (mTitle.equals("故事")) {
            getList("1", sBookPage);
        } else {
            Log.e("lee", "onActivityCreated: get title failed");
        }
        bookAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Toast.makeText(getActivity(),"暂无详情页哦，我们还在努力！",Toast.LENGTH_SHORT).show();
            }
        });
        bookAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mTitle.equals("教育")) {
                    edBookPage++;
                    if (bookAdapter.getData().size() < 20) {
                        bookAdapter.loadMoreEnd();
                    } else {
                        loadMoreList("0", edBookPage);
                    }
                } else {
                    sBookPage++;
                    if (bookAdapter.getData().size() < 20) {
                        bookAdapter.loadMoreEnd();
                    } else {
                        loadMoreList("1", sBookPage);
                    }
                }
            }
        }, rvBook);
    }

    @Override
    public void initViews() {
        Log.e("lee", "initViews: is init ");
    }

    @Override
    public void initData() {

    }

    private void getList(String type, int page) {
        bookList.clear();
        disposable.add(
                RetrofitFactory
                        .getInstance()
                        .getBookList(type, page)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (!NetUtil.isNetConnected(getActivity())) {
                                    Toast.makeText(getActivity(), "　暂无网络！！！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<BaseEntity<BookListBean>>() {
                            @Override
                            public void accept(BaseEntity<BookListBean> bookListBeanBaseEntity) throws Exception {
                                Log.e("lee", "accept: success " + bookListBeanBaseEntity.getData().getList().toString());
                                tvAll.setText(String.format(getString(R.string.book_num), bookListBeanBaseEntity.getData().getCount()));
                                bookList.addAll(bookListBeanBaseEntity.getData().getList());
                                bookAdapter.notifyDataSetChanged();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                Log.e("lee", "accept: failed " + throwable.getMessage());
                            }
                        })
        );
    }

    private void loadMoreList(String type, int page) {
        disposable.add(
                RetrofitFactory
                        .getInstance()
                        .getBookList(type, page)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (!NetUtil.isNetConnected(getActivity())) {
                                    Toast.makeText(getActivity(), "　暂无网络！！！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<BaseEntity<BookListBean>>() {
                            @Override
                            public void accept(BaseEntity<BookListBean> bookListBeanBaseEntity) throws Exception {
                                Log.e("lee", "accept: success " + bookListBeanBaseEntity.getData().getList().toString());
                                bookList.addAll(bookListBeanBaseEntity.getData().getList());
                                if (bookListBeanBaseEntity.getData().getList().size() < 20) {
                                    bookAdapter.loadMoreEnd();
                                } else {
                                    bookAdapter.loadMoreComplete();
                                }
                                bookAdapter.notifyDataSetChanged();
                            }


                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                Log.e("lee", "accept: failed " + throwable.getMessage());
                                bookAdapter.loadMoreFail();
                            }
                        })
        );
    }
}